//
//  AppDelegate+EaseMob.m
//  EasMobSample
//
//  Created by dujiepeng on 12/5/14.
//  Copyright (c) 2014 dujiepeng. All rights reserved.
//
#define KNOTIFICATION_LOGINCHANGE @"loginStateChange"

#import "AppDelegate+EaseMob.h"
#import "CallViewController.h"
#import "MLHomeViewController.h"
#import "FindViewController.h"
/**
 *  本类中做了EaseMob初始化和推送等操作
 */

@implementation AppDelegate (EaseMob)

- (void)easemobApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if (launchOptions) {
        NSDictionary*userInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
        if(userInfo)
        {
            [self didReceiveRemoteNotification:userInfo];
        }
    }
    
    _connectionState = eEMConnectionConnected;
    
    [self registerRemoteNotification];
    
#warning SDK注册 APNS文件的名字, 需要与后台上传证书时的名字一一对应
    
    // 处理语音通话的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callOutWithChatter:) name:@"callOutWithChatter" object:nil];
    // 处理随机语音通话的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loversCallOutWithChatter:) name:@"loversCallOutWithChatter" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callControllerClose:) name:@"callControllerClose" object:nil];
   
    [[EaseMob sharedInstance] registerSDKWithAppKey:EASEMOB_APPKEY apnsCertName:EASEMOB_APNS_CERT_NAME otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    // 登录成功后，自动去取好友列表
    // SDK获取结束后，会回调
    // - (void)didFetchedBuddyList:(NSArray *)buddyList error:(EMError *)error方法。
    [[EaseMob sharedInstance].chatManager setIsAutoFetchBuddyList:YES];
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
    // 注册环信监听
    [self registerEaseMobNotification];
   
    [[EaseMob sharedInstance].chatManager enableDeliveryNotification];
    
    
    [[EaseMob sharedInstance] application:application
            didFinishLaunchingWithOptions:launchOptions];
    
    [self setupNotifiers];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, DeviceWidth, 44)];
        _networkStateView.backgroundColor = RGBA(151, 196, 248, 0.95);
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
         
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"network.disconnection", @"Network disconnection");
        [_networkStateView addSubview:label];
        
        _networkStateView.alpha = networkStatebool;
        
        [[UIApplication sharedApplication].delegate.window addSubview:_networkStateView];
    });


}

#pragma mark - IChatManagerDelegate 登录状态变化

- (void)didLoginFromOtherDevice
{
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
        
        if(error){
            [HUD Prompt:@"网络错误"];
        }else{
            UITabBarController *tabbar = (UITabBarController*)self.window.rootViewController;
            tabbar.selectedIndex = 1;
            
            
            [HUD Prompt:@"您的账号在别的地方登录"];
            [Utils alert:@"您的账号在别的地方登录"];
            //退出登录
            [Utils quitLogin];
            
           
        }
        
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"loginAtOtherDevice", @"your login account has been in other places") delegate:self cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
        //        alertView.tag = 100;
        //        [alertView show];
       
        
    } onQueue:nil];
}


- (void)didRemovedFromServer
{
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"loginUserRemoveFromServer", @"your account has been removed from the server side") delegate:self cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
//        alertView.tag = 101;
//        [alertView show];
    } onQueue:nil];
}

- (void)didUpdateBuddyList:(NSArray *)buddyList
            changedBuddies:(NSArray *)changedBuddies
                     isAdd:(BOOL)isAdd
{
    if (!isAdd)
    {
        NSMutableArray *deletedBuddies = [NSMutableArray array];
        for (EMBuddy *buddy in changedBuddies)
        {
            if ([buddy.username length])
            {
                [deletedBuddies addObject:buddy.username];
            }
        }
        if (![deletedBuddies count])
        {
            return;
        }
        
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loadFriendsData" object:self userInfo:nil];
}

- (void)didRemovedByBuddy:(NSString *)username
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loadFriendsData" object:self userInfo:nil];
}

- (void)didAcceptedByBuddy:(NSString *)username
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loadFriendsData" object:self userInfo:nil];
}

- (void)didAcceptBuddySucceed:(NSString *)username
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loadFriendsData" object:self userInfo:nil];
}

// 统计未读消息数
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[[EaseMob sharedInstance] chatManager] conversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:unreadCount];
}

- (void)didUpdateConversationList:(NSArray *)conversationList
{
    [self setupUnreadMessageCount];
}

// 未读消息数量变化回调
-(void)didUnreadMessagesCountChanged
{
    [self setupUnreadMessageCount];
}


- (void)disposeChatMessage:(EMMessage *)message
{
    if (message.from&&[message.from isEqualToString:@"new_sweet"]) {
        //收到对方同意添加恋人//或者删除恋人
        [self addSweet:message];
    }else if (message.from&&[message.from isEqualToString:@"new_friend"]) {
        //收到对方同意添加好友//或者删除好友
        [self addFriend:message];
    }else if (message.from&&[message.from isEqualToString:@"mlsystem"]){
        //收到 后台处理相关信息
        [self backstageDispose:message];
    }else if(message.from){
        NSArray *arr = message.messageBodies;
        if (arr) {
            NSString *nickname = [message.ext objectForKey:@"nickname"];
            EMCommandMessageBody *body= message.messageBodies.lastObject;
            if(body.action&&[body.action isEqualToString:ACTION_Pocketsweet_SwEET_IMG]){
                //对方修改了背景图片
                if (message.ext) {
                    NSString *url = [message.ext objectForKey:@"url"];
                    [self changeSweetheartViewBackgroundObjectId:message.from url:url];
                }
                
                
                
            }
        }
    }
}
- (void)changeSweetheartViewBackgroundObjectId:(NSString *)objectId url:(NSString *)url
{
    
    if ([ShareData shareData].firstView.sweetheart) {
        if ([[ShareData shareData].firstView.sweetheartUser.objectId isEqualToString:objectId]) {
            [[ShareData shareData].firstView changeBackgroundUrl:url];
        }
    }
    if ([ShareData shareData].secondView.sweetheart) {
        if ([[ShareData shareData].secondView.sweetheartUser.objectId isEqualToString:objectId]) {
            [[ShareData shareData].secondView changeBackgroundUrl:url];
        }
    }
    if ([ShareData shareData].thirdView.sweetheart) {
        if ([[ShareData shareData].thirdView.sweetheartUser.objectId isEqualToString:objectId]) {
            [[ShareData shareData].thirdView changeBackgroundUrl:url];
        }
    }
    
    
}

-(void)didReceiveCmdMessage:(EMMessage *)message
{
    NSDictionary *dic=@{@"message":message};
    [self disposeChatMessage:message];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cmd" object:self userInfo:dic];
    
}
//收到 后台处理相关信息
- (void)backstageDispose:(EMMessage *)message
{
    NSArray *arr = message.messageBodies;
    if (arr) {
        EMCommandMessageBody *body= message.messageBodies.lastObject;
        if (body.action) {
            if ([body.action isEqualToString:ACTION_AUTHENTICATE_SUCCEED]||[body.action isEqualToString:ACTION_FORBIDDEN_USER]||[body.action isEqualToString:ACTION_RESET_USER]) {
                //申请成为专属恋人结果 //禁言
                MLUser *user = [MLUser currentUser];
                if(user){
                    if ([body.action isEqualToString:ACTION_RESET_USER]||[body.action isEqualToString:ACTION_AUTHENTICATE_SUCCEED]) {
                        //通知他们改变状态
                        [Utils changeUserDataSendUsers];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartChange" object:self userInfo:nil];
                    }
                    if([body.action isEqualToString:ACTION_AUTHENTICATE_SUCCEED]){
                        
                        AVInstallation *installation = [AVInstallation currentInstallation];
                        NSArray *objects;
                        if (user.type == MLUserType_NORMAL) {
                            objects = @[user.objectId];
                        }else if (user.gender==MLUserGender_MALE) {
                            objects = @[user.objectId,@"SweetMale"];
                        }else{
                            objects = @[user.objectId,@"SweetFemale"];
                        }
                        [installation addUniqueObjectsFromArray:objects forKey:@"channels"];
                        [installation saveInBackground];
                    }
                    //刷新用户信息
                    [[MLUser currentUser] refreshInBackgroundWithBlock:nil];
                }
            }else if ([body.action isEqualToString:ACTION_DISABLE_USER]){
                //封号
                [self appout];
                
            }
        }
        
    }
}
- (void)addShareDateSweetsObjectId:(NSString *)objectId
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartChange" object:self userInfo:nil];

}
- (void)addShareDateFriendsObjectId:(NSString *)objectId
{
    [[MLUser currentUser] follow:objectId andCallback:^(BOOL succeeded, NSError *error) {
        
    }];
    
    //添加为好友
    
    if ([ShareData shareData].friends) {
        //判断是否已经是好友
        BOOL is = NO;
        for (MLUser *f in [ShareData shareData].friends) {
            if([f.objectId isEqualToString:objectId]){
                is = YES;
                break;
            }
        }
        
        if (!is) {
            //以前不是好友,查询到资料添加为好友
            if ([ShareData shareData].friends&&[ShareData shareData].friends.count) {
                AVQuery *q = [MLUser query];
                [q whereKey:@"objectId" equalTo: objectId];
                [q getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                    MLUser *user = (MLUser *)object;
                    [[ShareData shareData].friends addObject:user];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMyFriendsData" object:self userInfo:nil];
                    [Utils savePassFriendObjectID:objectId];
                }];
            }else{
               [Utils savePassFriendObjectID:objectId];
            }
            
            
        }else{
              [Utils savePassFriendObjectID:objectId];
        }
    }
  
    
}
//删除恋人记录
- (void)deleteShareDateSweetObjectId:(NSString *)objectId
{
    if([ShareData shareData].firstView.sweetheart){
        if ([[ShareData shareData].firstView.sweetheartUser.objectId isEqualToString:objectId]) {
            [[ShareData shareData].firstView logOut];
        }
    }
    if([ShareData shareData].secondView.sweetheart){
        if ([[ShareData shareData].secondView.sweetheartUser.objectId isEqualToString:objectId]) {
            [[ShareData shareData].secondView logOut];
        }
    }
    if([ShareData shareData].thirdView.sweetheart){
        if ([[ShareData shareData].thirdView.sweetheartUser.objectId isEqualToString:objectId]) {
            [[ShareData shareData].thirdView logOut];
        }
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartChange" object:self userInfo:nil];
}
//删除好友记录
- (void)deleteShareDateFriendsObjectId:(NSString *)objectId
{
    if ([ShareData shareData].friends) {
        
        //删除好友
        for (int i = 0; i<[ShareData shareData].friends.count; i++) {
            MLUser *n = [[ShareData shareData].friends objectAtIndex:i];
            if ([n.objectId isEqualToString:objectId]) {
                [[ShareData shareData].friends removeObjectAtIndex:i];
                break;
            }
        }
    }
    [Utils removeObjectForFriendObjectID:objectId];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMyFriendsData" object:self userInfo:nil];
}
//收到对方同意添加恋人//或者删除恋人
- (void)addSweet:(EMMessage *)message
{
    NSArray *arr = message.messageBodies;
    if (arr) {
        EMCommandMessageBody *body= message.messageBodies.lastObject;
        if (body.action && [body.action isEqualToString:ACTION_Pocketsweet_SWEET_ACCEPT]) {
            NSDictionary *ext = message.ext;
            if ([ext objectForKey:@"from"]) {
                [self addShareDateSweetsObjectId:[ext objectForKey:@"from"]];
            }
        }else if (body.action && [body.action isEqualToString:ACTION_Pocketsweet_SWEET_DELETE]){
            NSDictionary *ext = message.ext;
            if ([ext objectForKey:@"from"]) {
              
                
                [self deleteShareDateSweetObjectId:[ext objectForKey:@"from"]];
            }
        }
    }
}
//收到对方同意添加好友//或者删除好友
- (void)addFriend:(EMMessage *)message
{
    NSArray *arr = message.messageBodies;
    if (arr) {
        EMCommandMessageBody *body= message.messageBodies.lastObject;
        if (body.action && [body.action isEqualToString:ACTION_FRIEND_APPLY_ACCEPTED]) {
            NSDictionary *ext = message.ext;
            if ([ext objectForKey:@"from"]) {
                 [self addShareDateFriendsObjectId:[ext objectForKey:@"from"]];
            }
        }else if (body.action && [body.action isEqualToString:ACTION_FRIEND_DELETE]){
            NSDictionary *ext = message.ext;
            if ([ext objectForKey:@"from"]) {
                //删除回话
                [[EaseMob sharedInstance].chatManager removeConversationByChatter:[ext objectForKey:@"from"] deleteMessages:YES append2Chat:YES];
                // 删除好友
                [self deleteShareDateFriendsObjectId:[ext objectForKey:@"from"]];
            }
        }
    }
}
//插入一个小灰条,只能本人看到
- (void)interpositionMessageText:(NSString *)text andUserObjectId:(NSString *)objectId
{
    NSDictionary *ext = @{@"type": @EMMESSAGE_EXT_TYPE_CHAT_NOTIFICATION_MSG};
    EMChatText *txt = [[EMChatText alloc] initWithText:text];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txt];
    EMMessage *message = [[EMMessage alloc] initWithReceiver:objectId bodies:@[body]];
    message.ext = ext;
    message.isRead = NO;
    message.messageType = eMessageTypeChat; // 设置为单聊消息
    message.deliveryState = eMessageDeliveryState_Delivered;
    [[EaseMob sharedInstance].chatManager insertMessageToDB:message append2Chat:YES];
    [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
    NSDictionary *dic=@{@"message":message ,@"objectId":objectId};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addHintMessage" object:self userInfo:dic];
}
- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages
{
    [self setupUnreadMessageCount];
    
}
- (void)didReceiveOfflineCmdMessages:(NSArray *)offlineCmdMessages;
{
    
    for (EMMessage *message  in offlineCmdMessages) {
        [self disposeChatMessage:message];
        
    }
}
//离线非透传消息接收完成的回调
- (void)didFinishedReceiveOfflineMessages
{
    
}
//离线透传消息接收完成的回调
- (void)didFinishedReceiveOfflineCmdMessages
{
    
}
- (void)didFinishedReceiveOfflineMessages:(NSArray *)offlineMessages
{
   
}
//离线透传消息会走以下回调:
- (void)didFinishedReceiveOfflineCmdMessages:(NSArray *)offlineCmdMessages;
{
   
    
    
}

-(void)didReceiveMessage:(EMMessage *)message
{    
    id<IEMMessageBody> messageBody = message.messageBodies.lastObject;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"message" object:self userInfo:nil];
    NSDictionary *dic=@{@"message":message};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"receiveMessage" object:self userInfo:dic];
    if (messageBody.message.ext != nil) {
        if ([[messageBody.message.ext objectForKey:@"notification"]isEqualToString:EMMESSAGE_EXT_TYPE_JITTER_APPLY]){
            //未读的震动
            if (!messageBody.message.isRead) {
                messageBody.message.isRead = YES;
                [HUD shakeAnimationForView:self.window];
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            }
        }else if([messageBody.message.ext objectForKey:LITTLE_ACTION_TYPE_MOMODA]&&[[messageBody.message.ext objectForKey:LITTLE_ACTION_TYPE_MOMODA]isEqualToString:LITTLE_ACTION_TYPE_MOMODA_VALUE]){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartMessage" object:self userInfo:dic];
            
        }else if([messageBody.message.ext objectForKey:LITTLE_ACTION_TYPE_CHUO]&&[[messageBody.message.ext objectForKey:LITTLE_ACTION_TYPE_CHUO]isEqualToString:LITTLE_ACTION_TYPE_CHUO_VALUE]){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartMessage" object:self userInfo:dic];
            
        }
    }
    
    BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
    
    if (!isAppActivity) {
      
        //实现本地通知
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        if (notification) {
            // 设置通知的提醒时间
            NSDate *currentDate   = [NSDate date];
            notification.timeZone = [NSTimeZone defaultTimeZone]; // 使用本地时区
            notification.fireDate = [currentDate dateByAddingTimeInterval:0];
            // 设置重复间隔
            notification.repeatInterval = 0;
            // 设置提醒的文字内容
            notification.alertBody   = @"一条新消息";
            //notification.alertAction = NSLocalizedString(@"你有一条新短消息", nil);
            // 通知提示音 使用默认的
            notification.soundName= UILocalNotificationDefaultSoundName;
            // 将通知添加到系统中
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
    }
  
}
//5567c326e4b046f4d982d10e
//打电话
- (void)callOutWithChatter:(NSNotification *)notification
{
    if (![[EaseMob sharedInstance].chatManager isConnected]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginEaseMob" object:self userInfo:nil];
        return;
    }
    
    id object = notification.object;
    MLUser *chatUser = [object objectForKey:@"chatUser"];
    NSString *str = [NSString stringWithFormat:@"%@请求和你通话",[MLUser currentUser].nickname];
    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                         str, @"alert",
                          @"default", @"sound",NOTIFICATION_TYPE_NEW_CALL_PUSH,@"action",
                          nil];
   // NSDictionary *data = @{@"aps":@{@"alert":str,@"badge":@"Increment",@"sound":@"default"}};
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        AVPush *push = [[AVPush alloc] init];
        //正式需要注销下面一行代码
        //[AVPush setProductionMode:NO];
        [push setChannels:[NSArray arrayWithObjects:chatUser.objectId, nil]];
        [push setData:data];
        [push sendPushInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
           
        }];
    });
    if ([object isKindOfClass:[NSDictionary class]]) {
        if (![self canRecord]) {
            //[ShareData shareData].callVC = nil;
            return;
        }
        NSString *chatter = [object objectForKey:@"chatter"];
        EMCallSessionType type = [[object objectForKey:@"type"] intValue];
        EMCallSession *callSession = nil;
        BOOL isSponsor = [[object objectForKey:@"isSponsor"] boolValue];
        
        if (isSponsor) {
            [[MLUser currentUser] refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                MLUser *User = (MLUser*)object;
               
             
                if (User.balance >= 0.2) {
                    [self callPhoneSession:callSession SessionType:type Chatter:chatter ChatUser:chatUser isSponsor:isSponsor];
                }else{
                    
                    [Utils alert:@"余额不足"];
                    return ;
                }
            }];
        }else{
            [self callPhoneSession:callSession SessionType:type Chatter:chatter ChatUser:chatUser isSponsor:isSponsor];
        }
    }
}
- (void)loversCallOutWithChatter:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        if (![[EaseMob sharedInstance].chatManager isConnected]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginEaseMob" object:self userInfo:nil];
            return;
        }
        
        EMError *error = nil;
        EMCallSessionType type = [[object objectForKey:@"type"] intValue];
        EMCallSession *callSession = nil;
        MLUser *chatUser = [object objectForKey:@"chatUser"];
        
        if (type == eCallSessionTypeAudio) {
            
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVoiceCall:chatUser.objectId timeout:0 error:&error];
        }
        else if (type == eCallSessionTypeVideo){
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVideoCall:chatUser.objectId timeout:0 error:&error];
        }
        
        if (callSession && !error) {
            
            if ([chatUser.objectId isKindOfClass:[NSString class]]) {
               [[EaseMob sharedInstance].callManager removeDelegate:self];
//                [[ShareData shareData].loverCallView session:callSession isIncoming:NO ChatUser:chatUser];
            }else{
                // [Utils alert:@"正在通话中"];
                return ;
            }
        }
        if (error) {
            //[HUD Prompt:@"通话失败"];
        }
    }
    
    
    
}
//打电话
-(void)callPhoneSession:(EMCallSession*)callSession SessionType:(EMCallSessionType)type Chatter:(NSString*)chatter ChatUser:(MLUser*)chatUser isSponsor:(BOOL)isSponsor
{
    
    if (![[EaseMob sharedInstance].chatManager isConnected]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginEaseMob" object:self userInfo:nil];
        return;
    }
    EMError *error = nil;
    if (type == eCallSessionTypeAudio) {
        
        callSession = [[EaseMob sharedInstance].callManager asyncMakeVoiceCall:chatter timeout:0 error:&error];
    }
    else if (type == eCallSessionTypeVideo){
        if (![CallViewController canVideo]) {
            return;
        }
        callSession = [[EaseMob sharedInstance].callManager asyncMakeVideoCall:chatter timeout:0 error:&error];
    }
    
    if (callSession && !error) {
        
        if ([chatter isKindOfClass:[NSString class]]) {
            [[EaseMob sharedInstance].callManager removeDelegate:self];
            CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:NO];
            callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self.window.rootViewController presentViewController:callController animated:NO completion:nil];
        }else{
            [Utils alert:@"正在通话中"];
            return ;
        }
    }
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", @"error") message:error.description delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
        [alertView show];
        //[HUD Prompt:@"通话失败"];
    }
}
//取消电话
- (void)callControllerClose:(NSNotification *)notification
{
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}

//接听电话
- (void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error
{
    if (![[EaseMob sharedInstance].chatManager isConnected]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginEaseMob" object:self userInfo:nil];
        return;
    }
//    if (callSession.type == eCallSessionTypeVideo) {
//        //随机电话
////        if([ShareData shareData].loversCall){
////            if (callSession.status == eCallSessionStatusConnected)
////            {
////                EMError *error = nil;
////                do {
////                    BOOL isShowPicker = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isShowPicker"] boolValue];
////                    if (isShowPicker) {
////                        error = [EMError errorWithCode:EMErrorInitFailure andDescription:@"不能进行通话"];
////                        break;
////                    }
////                    
////                    if (![self canRecord]) {
////                        error = [EMError errorWithCode:EMErrorInitFailure andDescription:@"不能进行通话"];
////                        break;
////                    }
////                    
//////#warning 在后台不能进行视频通话
////                    //                if(callSession.type == eCallSessionTypeVideo && ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground || ![CallViewController canVideo])){
////                    //                    error = [EMError errorWithCode:EMErrorInitFailure andDescription:@"不能进行视频通话"];
////                    //                    break;
////                    //                }
////                    
////                    
////                    if (!isShowPicker){
////                        [[EaseMob sharedInstance].callManager removeDelegate:self];
////                        [[ShareData shareData].loverCallView session:callSession isIncoming:YES ChatUser:nil];
////                    }
////                } while (0);
////                
////                if (error) {
////                    [[EaseMob sharedInstance].callManager asyncEndCall:callSession.sessionId reason:eCallReason_Hangup];
////                    return;
////                }
////            }
////        }else{
////            [[EaseMob sharedInstance].callManager asyncEndCall:callSession.sessionId reason:eCallReason_Reject];
////            //随机电话,但是不在随机页面
////           
////            
////        }
//        
//    }else if(callSession.type == eCallSessionTypeAudio&&![ShareData shareData].loversCall){
//        
//        if (callSession.status == eCallSessionStatusConnected)
//        {
//            EMError *error = nil;
//            do {
//                BOOL isShowPicker = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isShowPicker"] boolValue];
//                if (isShowPicker) {
//                    error = [EMError errorWithCode:EMErrorInitFailure andDescription:@"不能进行通话"];
//                    break;
//                }
//                
//                if (![self canRecord]) {
//                    error = [EMError errorWithCode:EMErrorInitFailure andDescription:@"不能进行通话"];
//                    break;
//                }
//                
//#warning 在后台不能进行视频通话
//                if(callSession.type == eCallSessionTypeVideo && ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground || ![CallViewController canVideo])){
//                    error = [EMError errorWithCode:EMErrorInitFailure andDescription:@"不能进行视频通话"];
//                    break;
//                }
//                
//                if (!isShowPicker){
//                    [[EaseMob sharedInstance].callManager removeDelegate:self];
//                    CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:YES ChatUser:nil];
//                    callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
//                    [self.window.rootViewController presentViewController:callController animated:YES completion:nil];
//                    
//                }
//            } while (0);
//            
//            if (error) {
//                [[EaseMob sharedInstance].callManager asyncEndCall:callSession.sessionId reason:eCallReason_Hangup];
//                return;
//            }
//        }
//    }else{
//        //不处理
//        NSLog(@"bu");
//        [[EaseMob sharedInstance].callManager asyncEndCall:callSession.sessionId reason:eCallReason_Reject];
//    }
}

- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    if (!bCanRecord) {
        UIAlertView * alt = [[UIAlertView alloc] initWithTitle:@"未获得授权使用麦克风" message:@"请在iOS\"设置中\"-\"隐私\"-\"麦克风\"中打开" delegate:self cancelButtonTitle:nil otherButtonTitles:@"知道了", nil];
        [alt show];
    }
    
    return bCanRecord;
}

// 监听系统生命周期回调，以便将需要的事件传给SDK
- (void)setupNotifiers{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackgroundNotif:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidFinishLaunching:)
                                                 name:UIApplicationDidFinishLaunchingNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidBecomeActiveNotif:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillResignActiveNotif:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidReceiveMemoryWarning:)
                                                 name:UIApplicationDidReceiveMemoryWarningNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillTerminateNotif:)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataWillBecomeUnavailableNotif:)
                                                 name:UIApplicationProtectedDataWillBecomeUnavailable
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataDidBecomeAvailableNotif:)
                                                 name:UIApplicationProtectedDataDidBecomeAvailable
                                               object:nil];
}

#pragma mark - notifiers
- (void)appDidEnterBackgroundNotif:(NSNotification*)notif{
    [[EaseMob sharedInstance] applicationDidEnterBackground:notif.object];
}

- (void)appWillEnterForeground:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillEnterForeground:notif.object];
}

- (void)appDidFinishLaunching:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidFinishLaunching:notif.object];
}

- (void)appDidBecomeActiveNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidBecomeActive:notif.object];
}

- (void)appWillResignActiveNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillResignActive:notif.object];
}

- (void)appDidReceiveMemoryWarning:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidReceiveMemoryWarning:notif.object];
}

- (void)appWillTerminateNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillTerminate:notif.object];
}

- (void)appProtectedDataWillBecomeUnavailableNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationProtectedDataWillBecomeUnavailable:notif.object];
}

- (void)appProtectedDataDidBecomeAvailableNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationProtectedDataDidBecomeAvailable:notif.object];
}

// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    AVInstallation *installation = [AVInstallation currentInstallation];
    [installation setDeviceTokenFromData:deviceToken];
    // NSArray *subscribedChannels = [AVInstallation currentInstallation].channels;
    [installation addUniqueObject:@"public" forKey:@"channels"];
    [installation saveInBackground];
    [installation saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
      //  NSLog(@"error%@",error);
    }];
   // NSLog(@"%@",subscribedChannels);
    [[EaseMob sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

// 注册deviceToken失败，此处失败，与环信SDK无关，一般是您的环境配置或者证书配置有误
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    [[EaseMob sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
    NSLog(@"注册deviceToken失败 error -- %@",error);
}

// 注册推送
- (void)registerRemoteNotification{
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber = 0;
    
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
#if !TARGET_IPHONE_SIMULATOR
    //iOS8 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
#endif
}

#pragma mark - registerEaseMobNotification
- (void)registerEaseMobNotification{
    [self unRegisterEaseMobNotification];
    // 将self 添加到SDK回调中，以便本类可以收到SDK回调
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
}

- (void)unRegisterEaseMobNotification{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}



#pragma mark - IChatManagerDelegate
// 开始自动登录回调
-(void)willAutoLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error
{
    if (!error) {
        //将旧版的coredata数据导入新的数据库
        EMError *error = [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
        if (!error) {
            error = [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
        }
    }
}
// 申请加入群组被拒绝回调
- (void)didReceiveRejectApplyToJoinGroupFrom:(NSString *)fromId
                                   groupname:(NSString *)groupname
                                      reason:(NSString *)reason
                                       error:(EMError *)error{
    if (!reason || reason.length == 0) {
        reason = [NSString stringWithFormat:NSLocalizedString(@"group.beRefusedToJoin", @"be refused to join the group\'%@\'"), groupname];
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:reason delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
    [alertView show];
}

// 已经同意并且加入群组后的回调
- (void)didAcceptInvitationFromGroup:(EMGroup *)group
                               error:(EMError *)error
{
    if(error)
    {
        return;
    }
    
    NSString *groupTag = group.groupSubject;
    if ([groupTag length] == 0) {
        groupTag = group.groupId;
    }
    
    NSString *message = [NSString stringWithFormat:NSLocalizedString(@"group.agreedAndJoined", @"agreed and joined the group of \'%@\'"), groupTag];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
    [alertView show];
}


// 绑定deviceToken回调
- (void)didBindDeviceWithError:(EMError *)error
{
    if (error) {
        [Utils alert:NSLocalizedString(@"apns.failToBindDeviceToken", @"Fail to bind device token")];
    }
}

// 网络状态变化回调
- (void)didConnectionStateChanged:(EMConnectionState)connectionState
{
    _connectionState = connectionState;
    [[ShareData shareData].chatlistVC networkChanged:connectionState];
    
    if (connectionState == eEMConnectionDisconnected) {
        if (_networkStateView.alpha == 0) {
            [Utils Hidden:_networkStateView Bool:YES];
            networkStatebool = YES;
        }
    }else{
        if (_networkStateView.alpha == 1) {
            [Utils Hidden:_networkStateView Bool:NO];
            networkStatebool = NO;
        }
    }
}


// 打印收到的apns信息
-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo
{
//    NSError *parseError = nil;
//    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo
//                                                        options:NSJSONWritingPrettyPrinted error:&parseError];
//    NSString *str =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"推送内容"
//                                                    message:str
//                                                   delegate:nil
//                                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
//                                          otherButtonTitles:nil];
//    [alert show];
    
}

@end
